//
//  PLSimpleChatController.m
//  Plankton
//
//  Created by Marc Schlichte on 19.07.08.
//  Copyright 2008 Framework Labs. All rights reserved.
//

#import "PLSimpleChatController.h"

#import "PLPlatform.h"
#import "PLDirectory.h"
#import "PLSimpleChatRoom.h"


@interface PLSimpleChatController (InternalMethods)

- (void)onChatRoomSelectionChanged;

@end

@implementation PLSimpleChatController

@synthesize ownAid, nickname;
@synthesize chatRooms, currentChatRoom;
@synthesize receivedText, sendText;

- (id)init
{
    if (self = [super init]) {        
        platform = [[PLPlatform alloc] init];
        self.ownAid = [platform createAid];
        
        directory = [[PLDirectory alloc] initWithPlatform:platform];
        directory.delegate = self;
        directory.discoverable = YES;
        directory.autoDiscover = YES;
        
        ownChatRoom = [[PLSimpleChatRoom alloc] initWithPlatform:platform];
        [directory registerAid:ownChatRoom.chatRoomAid forService:@"plankton.simplechat"];

        chatRooms = [[NSMutableSet alloc] init]; 
        [directory searchAidsForService:@"plankton.simplechat"];
        
        self.nickname = ownAid;
        receivedText = @"";
        sendText = @"";   
        
        receivePattern = [[PLPattern patternAny] retain];
        [receivePattern setMessageTarget:self action:@selector(onChatMessage:pattern:)];
        
        [platform receive:receivePattern by:ownAid];
    }
    return self;
}

- (void)awakeFromNib
{
    // observere the chat-room-array-controller selection property
    [chatRoomController addObserver:self forKeyPath:@"selection" options:0 context:nil];
}

- (void)dealloc
{
    [chatRoomController removeObserver:self forKeyPath:@"selection"];
    
    [ownChatRoom release];
    [currentChatRoom release];
    [receivePattern release];
    [ownAid release];
    [nickname release];
    [chatRooms release];
    [sendText release];
    [receivedText release];
    [directory release];
    [platform release];
    
    [super dealloc];
}

- (IBAction)send:(id)sender
{
    @try {
        [platform send:[NSArray arrayWithObjects:@"inform", ownAid, sendText, nil] to:currentChatRoom];
        self.sendText = @"";
    }
    @catch(NSException *e) {
        self.sendText = [e description];
    }
}

- (void)onChatMessage:(id)message pattern:(PLPattern *)pat
{
    if ([receivedText isEqual:@""]) {
        self.receivedText = [NSString stringWithFormat:@"%@> %@", [message objectAtIndex:0], [message lastObject]];
    }
    else {
        self.receivedText = [NSString stringWithFormat:@"%@\n%@> %@", receivedText, [message objectAtIndex:0], [message lastObject]];
    }
    [textView scrollRangeToVisible:NSMakeRange([receivedText length], 1)];
    
    [platform receive:receivePattern by:ownAid];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    [self onChatRoomSelectionChanged];
}

- (void)onChatRoomSelectionChanged
{
    NSArray *selectedObjects = [chatRoomController selectedObjects];
    if ([selectedObjects count] > 0) {
        self.currentChatRoom = [selectedObjects objectAtIndex:0];
    }
    else {
        self.currentChatRoom = nil;
    }
}
         
- (void)setNickname:(NSString *)nick
{
    if (![nickname isEqual:nick]) {
        [nickname autorelease];
        nickname = [nick retain];
        if (currentChatRoom) {
            [platform send:[NSArray arrayWithObjects:@"changeNick", ownAid, nickname, nil] to:currentChatRoom];
        }
    }
}

- (void)setCurrentChatRoom:(NSString *)room
{
    if (![currentChatRoom isEqual:room]) {
        [self willChangeValueForKey:@"hasChatRoom"];
        if (currentChatRoom) {
            [platform send:[NSArray arrayWithObjects:@"leave", ownAid, nil] to:currentChatRoom];
            [currentChatRoom autorelease];
        }
        currentChatRoom = [room retain];
        self.receivedText = @"";
        if (currentChatRoom) {
            [platform send:[NSArray arrayWithObjects:@"join", ownAid, nickname, nil] to:currentChatRoom];
        }
        [self didChangeValueForKey:@"hasChatRoom"];
    }
}

- (BOOL)hasChatRoom
{
    return currentChatRoom != nil;
}

- (void)directory:(PLDirectory *)directory foundAid:(NSString *)aid forService:(NSString *)service
{
    [chatRooms addObject:aid];
}

- (void)directory:(PLDirectory *)directory searchDoneForService:(NSString *)service
{
    [self willChangeValueForKey:@"chatRooms"];
    [self didChangeValueForKey:@"chatRooms"];
}
         
- (void)directory:(PLDirectory *)directory foundServices:(NSSet *)services
{
    // todo: make this delegate method optional
}         

- (void)directoryChangedPeerSet:(PLDirectory *)directory_
{
    [chatRooms removeAllObjects];
    [directory searchAidsForService:@"plankton.simplechat"];
}

/* todo: not yet implemented
 - (void)directory:(PLDirectory *)directory addedAid:(NSString *)aid forService:(NSString *)service;
 - (void)directory:(PLDirectory *)directory removedAid:(NSString *)aid forService:(NSString *)service;
 */

@end
